package com.example.springaop3.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-03-15
 * Time: 23:25
 */
@ControllerAdvice // 不使用 @RestControllerAdvice 原因是 默认返回的就是数据
public class MyResponseAdvice implements ResponseBodyAdvice {

//    true 表示 要重写返回的数据的数据类型,执行 beforeBodyWrite 方法 否则不操作, 直接返回
//    可以根据这个函数进行筛选哪些需要重写, 哪些不需要
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String, Object> result=new HashMap<>();
        result.put("state", 1);
        result.put("data", body);
        result.put("msg", "");
        return result;
    }
}
